<template>
  <div class="time-slot-management">
    <div class="page-header">
      <h2>场馆时间段管理</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>
    
    <el-card shadow="never" v-loading="venueLoading">
      <template #header>
        <div class="card-header">
          <span>场馆信息</span>
        </div>
      </template>
      
      <el-descriptions :column="3" border>
        <el-descriptions-item label="场馆名称">{{ venueInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="场馆类型">{{ getVenueTypeText(venueInfo.type) }}</el-descriptions-item>
        <el-descriptions-item label="营业时间">{{ venueInfo.open_time }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="venueInfo.status === 1 ? 'success' : 'info'">
            {{ venueInfo.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="地址">{{ venueInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ venueInfo.contact_phone }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    
    <!-- 24小时时间段网格管理 -->
    <el-card shadow="never" class="timeslot-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>时间段价格管理（24小时视图）</span>
          <div class="legend">
            <span class="legend-item">
              <span class="legend-color set"></span>
              已设置
            </span>
            <span class="legend-item">
              <span class="legend-color unset"></span>
              未设置
            </span>
          </div>
        </div>
      </template>
      
      <!-- 日期选择和星期几选择 -->
      <div class="control-panel">
        <div class="date-selector">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期查看预订数据"
            style="margin-right: 20px;"
          />
          <span class="date-info" v-if="selectedDate">
            ({{ formatDateDisplay(selectedDate) }} {{ getDayOfWeekText(currentDay) }})
          </span>
        </div>
      <div class="day-selector">
          <span class="day-selector-label">时间段设置（按星期）：</span>
          <el-radio-group v-model="selectedDateString">
            <el-radio-button 
              v-for="day in weekDates" 
              :key="day.value" 
              :value="day.value"
            >
              {{ day.label }}
            </el-radio-button>
        </el-radio-group>
        </div>
      </div>
      
      <!-- 24小时网格 -->
      <div class="hours-grid">
        <div class="grid-header">
          <span>{{ getDayOfWeekText(currentDay) }} - 24小时时间段设置</span>

        </div>
        
        <div class="grid-container">
          <div 
            v-for="hour in 24" 
            :key="hour-1" 
            class="hour-slot"
            :class="{ 
              'has-setting': hasTimeSlot(hour-1),
              'no-setting': !hasTimeSlot(hour-1)
            }"
            @click="editTimeSlot(hour-1)"
          >
            <div class="hour-label">
              {{ String(hour-1).padStart(2, '0') }}:00-{{ String(hour).padStart(2, '0') }}:00
            </div>
            
            <div v-if="hasTimeSlot(hour-1)" class="slot-info">
              <div class="price">¥{{ getTimeSlotInfo(hour-1).price }}</div>
              <div class="capacity">{{ getTimeSlotInfo(hour-1).capacity }}人</div>
              <div class="booking-stats">
                <div class="booking-count">预订: {{ getBookingCount(getTimeSlotInfo(hour-1).id) }}人</div>
                <div class="attendance-count">到场: {{ getAttendanceCount(getTimeSlotInfo(hour-1).id) }}人</div>
              </div>
              <div class="status">
                <el-tag :type="getTimeSlotInfo(hour-1).status === 1 ? 'success' : 'info'" size="small">
                  {{ getTimeSlotInfo(hour-1).status === 1 ? '开放' : '关闭' }}
                </el-tag>
              </div>
            </div>
            
            <div v-else class="no-setting-text">
              点击设置
            </div>
          </div>
        </div>
      </div>
      
      <!-- 批量操作 -->
      <div class="batch-operations">
        <el-button type="primary" @click="batchSetPrice">批量设置价格</el-button>
        <el-button type="success" @click="copyFromOtherDay">从其他星期复制</el-button>
        <el-button type="warning" @click="clearAllSlots">清空当天设置</el-button>
      </div>
    </el-card>
    
    <!-- 时间段设置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingSlot ? '编辑时间段' : '设置时间段'"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="dialog-header">
        <h4>{{ getDayOfWeekText(currentDay) }} {{ String(editingHour).padStart(2, '0') }}:00-{{ String(editingHour + 1).padStart(2, '0') }}:00</h4>
      </div>
      
      <el-form
        ref="slotFormRef"
        :model="slotForm"
        :rules="slotRules"
        label-width="100px"
      >
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="slotForm.price" 
            :min="0" 
            :precision="2" 
            :step="10" 
            style="width: 100%"
            placeholder="请输入价格"
          />
          <span style="margin-left: 10px; color: #909399;">元</span>
        </el-form-item>
        
        <el-form-item label="容量" prop="capacity">
          <el-input-number 
            v-model="slotForm.capacity" 
            :min="1" 
            :step="1" 
            style="width: 100%"
            placeholder="请输入容量"
          />
          <span style="margin-left: 10px; color: #909399;">人</span>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="slotForm.status">
            <el-radio :value="1">开放</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button v-if="editingSlot" type="danger" @click="deleteTimeSlot">删除</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 批量设置价格对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="批量设置价格"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px" v-loading="batchLoading">
        <el-form-item label="价格">
          <el-input-number 
            v-model="batchPrice" 
            :min="0" 
            :precision="2" 
            :step="10" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="容量">
          <el-input-number 
            v-model="batchCapacity" 
            :min="1" 
            :step="1" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="应用范围">
          <el-checkbox-group v-model="batchHours">
            <div class="batch-hours-grid styled-batch-grid">
              <el-checkbox 
                v-for="hour in 24" 
                :key="hour-1" 
                :label="hour-1"
                :value="hour-1"
              >
                {{ String(hour-1).padStart(2, '0') }}:00
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDialogVisible = false" :disabled="batchLoading">取消</el-button>
          <el-button type="primary" @click="applyBatchSetting" :loading="batchLoading" :disabled="batchLoading">应用设置</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 复制其他星期对话框 -->
    <el-dialog
      v-model="copyDialogVisible"
      title="从其他星期复制设置"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px" v-loading="copyLoading">
        <el-form-item label="复制来源">
          <el-select v-model="copyFromDay" placeholder="请选择星期" style="width: 100%">
            <el-option 
              v-for="day in 7" 
              :key="day" 
              :label="getDayOfWeekText(day)" 
              :value="day"
              :disabled="day === currentDay"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-alert
            title="注意：复制操作会覆盖当前星期的所有设置"
            type="warning"
            :closable="false"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="copyDialogVisible = false" :disabled="copyLoading">取消</el-button>
          <el-button type="primary" @click="applyCopySettings" :loading="copyLoading" :disabled="copyLoading">确认复制</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'TimeSlotManagement',
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 使用computed来动态获取场馆ID，确保路由变化时能正确更新
    const venueId = computed(() => route.params.id)
    

    

    
    // 场馆信息
    const venueLoading = ref(false)
    const venueInfo = reactive({})
    
    // 时间段数据
    const loading = ref(false)
    const timeSlots = ref([])
    
    // 预订统计相关 - 默认显示今天
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const selectedDate = ref(today)
    const bookingStats = ref({})
    
    // 初始化当前星期几（基于今天）
    const todayWeekday = today.getDay() // 0=周日, 1=周一, ..., 6=周六
    const initialDay = todayWeekday === 0 ? 7 : todayWeekday // 转换为 1=周一, 7=周日
    const currentDay = ref(initialDay) // 默认今天对应的星期几
    
    // 对话框相关
    const dialogVisible = ref(false)
    const batchDialogVisible = ref(false)
    const copyDialogVisible = ref(false)
    const submitLoading = ref(false)
    const slotFormRef = ref(null)
    
    // 编辑相关
    const editingSlot = ref(null)
    const editingHour = ref(0)
    
    // 表单数据
    const slotForm = reactive({
      price: 0,
      capacity: 1,
      status: 1
    })
    
    // 批量设置
    const batchPrice = ref(0)
    const batchCapacity = ref(1)
    const batchHours = ref([])
    
    // 复制设置
    const copyFromDay = ref(1)
    
    // 表单验证规则
    const slotRules = {
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' },
        { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
      ],
      capacity: [
        { required: true, message: '请输入容量', trigger: 'blur' },
        { type: 'number', min: 1, message: '容量不能小于1', trigger: 'blur' }
      ]
    }
    
    // 场馆类型选项
    const venueTypes = [
      { label: '篮球场', value: 'basketball' },
      { label: '足球场', value: 'football' },
      { label: '网球场', value: 'tennis' },
      { label: '羽毛球馆', value: 'badminton' },
      { label: '游泳馆', value: 'swimming' },
      { label: '乒乓球室', value: 'pingpong' }
    ]
    
    // 当前星期的时间段数据
    const currentDaySlots = computed(() => {
      return timeSlots.value.filter(slot => slot.day_of_week === currentDay.value)
    })
    
    // 批量设置相关loading
    const batchLoading = ref(false)
    const copyLoading = ref(false)
    const clearLoading = ref(false)
    
    // 获取场馆信息
    const fetchVenueInfo = async () => {
      if (!venueId.value || venueId.value === 'undefined') {

        return
      }
      
      venueLoading.value = true
      try {
        const token = localStorage.getItem('admin_token')

        const response = await request.get(`/v1/admin/venues/${venueId.value}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })

        Object.assign(venueInfo, response.data)
      } catch (error) {
        console.error('获取场馆信息失败', error)
        ElMessage.error('获取场馆信息失败: ' + (error.response?.data?.message || error.message))
      } finally {
        venueLoading.value = false
      }
    }
    
    // 获取时间段列表
    const fetchTimeSlots = async () => {
      if (!venueId.value || venueId.value === 'undefined') {

        return
      }
      
      loading.value = true
      try {
        const token = localStorage.getItem('admin_token')

        const response = await request.get(`/v1/admin/venues/${venueId.value}/time-slots`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        

        timeSlots.value = response.data.timeSlots || []
        
      } catch (error) {
        console.error('获取时间段列表失败', error)
        ElMessage.error('获取时间段列表失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.value = false
      }
    }
    
    // 加载预订统计数据
    const loadBookingStatistics = async () => {
      if (!venueId.value || venueId.value === 'undefined' || !selectedDate.value) {
        console.log('❌ 无效参数，跳过加载预订统计')
        return
      }
      
      try {
        const dateStr = formatDateDisplay(selectedDate.value)
        const apiUrl = `/v1/admin/venues/${venueId.value}/booking-statistics?date=${dateStr}`
        
        console.log('🔍 调用预订统计API:', apiUrl)
        console.log('📅 查询参数:', {
          venueId: venueId.value,
          date: dateStr,
          dayOfWeek: selectedDate.value.getDay() === 0 ? 7 : selectedDate.value.getDay()
        })
        
        const token = localStorage.getItem('admin_token')
        const response = await request.get(apiUrl, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        console.log('📊 API响应数据:', response.data)
        
        // 重置统计数据
        bookingStats.value = {}
        
        // 处理响应数据 - 修复：API返回的数据结构是 { data: { hourly_stats: [...] } }
        if (response.data && response.data.hourly_stats && Array.isArray(response.data.hourly_stats)) {
          for (const slot of response.data.hourly_stats) {
            bookingStats.value[slot.time_slot_id] = {
              booked_count: slot.booked_count || 0,
              attended_count: slot.attended_count || 0
            }
          }
        } else if (response.data && Array.isArray(response.data)) {
          // 兼容旧的数据格式
          for (const slot of response.data) {
            bookingStats.value[slot.time_slot_id] = {
              booked_count: slot.booked_count || 0,
              attended_count: slot.attended_count || 0
            }
          }
        } else {
          console.log('❌ API返回的数据格式不正确:', response.data)
        }
        
        console.log('📈 处理后的统计数据:', bookingStats.value)
        
        // 调试：显示前几个时间段的映射
        const daySlots = timeSlots.value.filter(slot => slot.day_of_week === currentDay.value)
        console.log('🎯 当前星期时间段列表（前6个）:')
        for (let i = 0; i < Math.min(6, daySlots.length); i++) {
          const slot = daySlots[i]
          const stats = bookingStats.value[slot.id] || { booked_count: 0, attended_count: 0 }
          console.log(`  ${i+1}. ID=${slot.id}, ${slot.start_time}-${slot.end_time} → 预订${stats.booked_count}人, 到场${stats.attended_count}人`)
        }
        
      } catch (error) {
        console.error('❌ 获取预订统计失败:', error)
        bookingStats.value = {}
      }
    }
    
    // 获取预订人数
    const getBookingCount = (timeSlotId) => {
      return bookingStats.value[timeSlotId]?.booked_count || 0
    }
    
    // 获取到场人数
    const getAttendanceCount = (timeSlotId) => {
      return bookingStats.value[timeSlotId]?.attended_count || 0
    }
    
    // 检查某小时是否已设置
    const hasTimeSlot = (hour) => {
      const startTime = String(hour).padStart(2, '0') + ':00'
      const endTime = String(hour + 1).padStart(2, '0') + ':00'
      
      return currentDaySlots.value.some(slot => 
        slot.start_time === startTime && slot.end_time === endTime
      )
    }
    
    // 获取某小时的时间段信息
    const getTimeSlotInfo = (hour) => {
      const startTime = String(hour).padStart(2, '0') + ':00'
      const endTime = String(hour + 1).padStart(2, '0') + ':00'
      
      return currentDaySlots.value.find(slot => 
        slot.start_time === startTime && slot.end_time === endTime
      )
    }
    
    // 编辑时间段（保留原函数以兼容其他地方的调用）
    const editTimeSlot = (hour) => {
      editingHour.value = hour
      const existingSlot = getTimeSlotInfo(hour)
      
      if (existingSlot) {
        editingSlot.value = existingSlot
        Object.assign(slotForm, {
          price: existingSlot.price,
          capacity: existingSlot.capacity,
          status: existingSlot.status
        })
      } else {
        editingSlot.value = null
        Object.assign(slotForm, {
          price: 0,
          capacity: 1,
          status: 1
        })
      }
      
      dialogVisible.value = true
    }
    
    // 获取星期文本
    const getDayOfWeekText = (day) => {
      const dayMap = {
        1: '周一',
        2: '周二', 
        3: '周三',
        4: '周四',
        5: '周五',
        6: '周六',
        7: '周日'
      }
      return dayMap[day] || day
    }
    
    // 格式化日期显示（修复时区问题）
    const formatDateDisplay = (date) => {
      if (!date) return ''
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    // 获取场馆类型文本
    const getVenueTypeText = (type) => {
      const found = venueTypes.find(item => item.value === type)
      return found ? found.label : type
    }
    
    // 取消操作
    const handleCancel = () => {
      dialogVisible.value = false
      resetForm()
    }
    
    // 重置表单
    const resetForm = () => {
      if (slotFormRef.value) {
        slotFormRef.value.resetFields()
      }
      editingSlot.value = null
      editingHour.value = 0
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!slotFormRef.value) return
      
      await slotFormRef.value.validate(async (valid) => {
        if (!valid) return
        
        submitLoading.value = true
        
        try {
          const startTime = String(editingHour.value).padStart(2, '0') + ':00'
          const endTime = String(editingHour.value + 1).padStart(2, '0') + ':00'
          
          const data = {
            dayOfWeek: currentDay.value,
            startTime: startTime,
            endTime: endTime,
            price: slotForm.price,
            capacity: slotForm.capacity,
            status: slotForm.status
          }
          
          const token = localStorage.getItem('admin_token')
          const headers = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
          
          if (editingSlot.value) {
            // 编辑现有时间段
            await request.put(`/v1/admin/time-slots/${editingSlot.value.id}`, data, { headers })
            ElMessage.success('更新成功')
          } else {
            // 新增时间段，但先检查是否已存在
            const existingSlot = getTimeSlotInfo(editingHour.value)
            if (existingSlot) {
              await request.put(`/v1/admin/time-slots/${existingSlot.id}`, data, { headers })
              ElMessage.success('更新成功')
            } else {
              await request.post(`/v1/admin/venues/${venueId.value}/time-slots`, data, { headers })
              ElMessage.success('添加成功')
            }
          }
          
          dialogVisible.value = false
          fetchTimeSlots() // 刷新列表
          
        } catch (error) {
          console.error('保存时间段失败', error)
          const errorMsg = error.response?.data?.message || error.message
          ElMessage.error('保存失败: ' + errorMsg)
        } finally {
          submitLoading.value = false
        }
      })
    }
    
    // 删除时间段
    const deleteTimeSlot = async () => {
      if (!editingSlot.value) return
      
      try {
        await ElMessageBox.confirm('确认删除这个时间段吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const token = localStorage.getItem('admin_token')
        await request.delete(`/v1/admin/time-slots/${editingSlot.value.id}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        ElMessage.success('删除成功')
        dialogVisible.value = false
        fetchTimeSlots() // 刷新列表
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除时间段失败', error)
          ElMessage.error('删除时间段失败: ' + (error.response?.data?.message || error.message))
        }
      }
    }
    
    // 批量设置价格
    const batchSetPrice = () => {
      batchPrice.value = 0
      batchCapacity.value = 1
      batchHours.value = []
      batchDialogVisible.value = true
    }
    
    // 应用批量设置
    const applyBatchSetting = async () => {
      if (batchHours.value.length === 0) {
        ElMessage.warning('请选择要设置的时间段')
        return
      }
      
      batchLoading.value = true
      try {
        const token = localStorage.getItem('admin_token')
        const headers = {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
        
        // 1. 先删除所有选中小时的原有设置
        for (const hour of batchHours.value) {
          const existingSlot = getTimeSlotInfo(hour)
          if (existingSlot) {
            try {
              await request.delete(`/v1/admin/time-slots/${existingSlot.id}`, { headers })
            } catch (error) {
              // 忽略删除失败
            }
          }
        }
        // 2. 再批量新增所有选中小时的新设置
        let successCount = 0
        let errorCount = 0
        for (const hour of batchHours.value) {
          try {
            const startTime = String(hour).padStart(2, '0') + ':00'
            const endTime = String(hour + 1).padStart(2, '0') + ':00'
            const data = {
              dayOfWeek: currentDay.value,
              startTime: startTime,
              endTime: endTime,
              price: batchPrice.value,
              capacity: batchCapacity.value,
              status: 1
            }
            await request.post(`/v1/admin/venues/${venueId.value}/time-slots`, data, { headers })
            successCount++
          } catch (error) {
            console.error(`设置时间段 ${hour}:00 失败:`, error)
            errorCount++
          }
        }
        if (errorCount === 0) {
          ElMessage.success(`批量设置成功，共设置 ${successCount} 个时间段`)
        } else {
          ElMessage.warning(`批量设置完成，成功 ${successCount} 个，失败 ${errorCount} 个`)
        }
        batchDialogVisible.value = false
        fetchTimeSlots()
      } catch (error) {
        console.error('批量设置失败', error)
        ElMessage.error('批量设置失败: ' + (error.response?.data?.message || error.message))
      } finally {
        batchLoading.value = false
      }
    }
    
    // 从其他星期复制
    const copyFromOtherDay = () => {
      copyFromDay.value = currentDay.value === 1 ? 2 : 1
      copyDialogVisible.value = true
    }
    
    // 应用复制设置
    const applyCopySettings = async () => {
      copyLoading.value = true
      try {
        await ElMessageBox.confirm('确认复制设置吗？这将覆盖当前星期的所有设置。', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const sourceSlots = timeSlots.value.filter(slot => slot.day_of_week === copyFromDay.value)
        
        if (sourceSlots.length === 0) {
          ElMessage.warning('源星期没有设置任何时间段')
          return
        }
        
        const token = localStorage.getItem('admin_token')
        const headers = {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
        
        // 先删除当前星期的所有设置
        for (const slot of currentDaySlots.value) {
          await request.delete(`/v1/admin/time-slots/${slot.id}`, { headers })
        }
        
        // 复制源星期的设置
        for (const slot of sourceSlots) {
          const data = {
            dayOfWeek: currentDay.value,
            startTime: slot.start_time,
            endTime: slot.end_time,
            price: slot.price,
            capacity: slot.capacity,
            status: slot.status
          }
          
          await request.post(`/v1/admin/venues/${venueId.value}/time-slots`, data, { headers })
        }
        
        ElMessage.success('复制设置成功')
        copyDialogVisible.value = false
        fetchTimeSlots()
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('复制设置失败', error)
          ElMessage.error('复制设置失败: ' + (error.response?.data?.message || error.message))
        }
      } finally {
        copyLoading.value = false
      }
    }
    
    // 清空当天设置
    const clearAllSlots = async () => {
      clearLoading.value = true
      try {
        await ElMessageBox.confirm('确认清空当天所有时间段设置吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const token = localStorage.getItem('admin_token')
        const headers = {
          'Authorization': `Bearer ${token}`
        }
        
        for (const slot of currentDaySlots.value) {
          await request.delete(`/v1/admin/time-slots/${slot.id}`, { headers })
        }
        
        ElMessage.success('清空成功')
        fetchTimeSlots()
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('清空失败', error)
          ElMessage.error('清空失败: ' + (error.response?.data?.message || error.message))
        }
      } finally {
        clearLoading.value = false
      }
    }
    
    // 返回列表页
    const goBack = () => {
      router.push('/venue/list')
    }
    
    // 监听路由变化
    watch(() => route.params.id, (newId, oldId) => {
      if (newId !== oldId && newId && newId !== 'undefined') {

        // 使用nextTick确保路由完全更新后再获取数据
        nextTick(() => {
          fetchVenueInfo()
          fetchTimeSlots()
          loadBookingStatistics()
        })
      }
    }, { immediate: false })
    
    // 内部标志，避免循环触发
    const isInternalUpdate = ref(false)
    
    // 监听日期变化
    watch(selectedDate, (newDate, oldDate) => {
      // 仅当日期确实改变时才执行
      if (newDate && (!oldDate || newDate.getTime() !== oldDate.getTime())) {
        // 当选择日期时，自动切换到对应的星期几（显示对应的时间段设置）
        const weekday = newDate.getDay() // 0=周日, 1=周一, ..., 6=周六
        const adjustedWeekday = weekday === 0 ? 7 : weekday // 转换为 1=周一, 7=周日
        currentDay.value = adjustedWeekday
        console.log(`选择日期: ${formatDateDisplay(newDate)}, 对应星期: ${adjustedWeekday}`)
        console.log('日期变化 → 切换星期设置并加载预订数据')
        
        // 加载选定日期的预订统计数据
        loadBookingStatistics()
      }
    })
    
    const weekDates = computed(() => {
      if (!selectedDate.value) return []
      const date = new Date(selectedDate.value)
      const dayOfWeek = date.getDay()
      const dayOffset = dayOfWeek === 0 ? 6 : dayOfWeek - 1 // 0 for Monday, 6 for Sunday

      const monday = new Date(date)
      monday.setHours(0, 0, 0, 0) // Normalize time
      monday.setDate(date.getDate() - dayOffset)

      const week = []
      for (let i = 0; i < 7; i++) {
        const d = new Date(monday)
        d.setDate(monday.getDate() + i)
        week.push({
          date: d,
          label: `${getDayOfWeekText(i + 1)} (${d.getMonth() + 1}/${d.getDate()})`,
          value: formatDateDisplay(d) // Use YYYY-MM-DD string as value
        })
      }
      return week
    })

    const selectedDateString = computed({
      get: () => formatDateDisplay(selectedDate.value),
      set: (val) => {
        const parts = val.split('-').map(Number)
        selectedDate.value = new Date(parts[0], parts[1] - 1, parts[2])
      }
    })
    
    onMounted(() => {
      fetchVenueInfo()
      fetchTimeSlots()
      loadBookingStatistics()
    })
    
    return {
      venueLoading,
      venueInfo,
      loading,
      timeSlots,
      currentDay,
      dialogVisible,
      batchDialogVisible,
      copyDialogVisible,
      submitLoading,
      slotFormRef,
      slotForm,
      slotRules,
      editingSlot,
      editingHour,
      batchPrice,
      batchCapacity,
      batchHours,
      copyFromDay,
      currentDaySlots,
      selectedDate,
      bookingStats,
      weekDates,
      selectedDateString,
      hasTimeSlot,
      getTimeSlotInfo,
      editTimeSlot,
      getDayOfWeekText,
      formatDateDisplay,
      getVenueTypeText,
      handleCancel,
      submitForm,
      deleteTimeSlot,
      batchSetPrice,
      applyBatchSetting,
      copyFromOtherDay,
      applyCopySettings,
      clearAllSlots,
      goBack,
      batchLoading,
      copyLoading,
      clearLoading,
      loadBookingStatistics,
      getBookingCount,
      getAttendanceCount
    }
  }
}
</script>

<style lang="scss" scoped>
.time-slot-management {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .legend {
    display: flex;
    gap: 15px;
    
    .legend-item {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 12px;
    }
    
    .legend-color {
      width: 16px;
      height: 16px;
      border-radius: 2px;
      border: 1px solid #ddd;
      
      &.set {
        background-color: #e8f5e8;
      }
      
      &.unset {
        background-color: #fff;
      }
    }
  }
  
  .timeslot-card {
    margin-top: 20px;
  }
  
  .control-panel {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 20px;
    
    .date-selector {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      gap: 10px;
      
      .date-info {
        color: #606266;
        font-size: 14px;
        font-weight: 500;
      }
    }
    
    .day-selector {
      flex: 1;
      text-align: center;
      
      .day-selector-label {
        color: #606266;
        font-size: 14px;
        margin-right: 10px;
        font-weight: 500;
      }
    }
  }
  
  .day-selector {
    margin-bottom: 20px;
    text-align: center;
  }
  
  .hours-grid {
    .grid-header {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      color: var(--text-primary);
    }
    
    .grid-container {
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      gap: 10px;
      margin-bottom: 20px;
      
      @media (max-width: 1200px) {
        grid-template-columns: repeat(4, 1fr);
      }
      
      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
      }
    }
    
    .hour-slot {
      border: 2px solid #e4e7ed;
      border-radius: 8px;
      padding: 12px;
      cursor: pointer;
      transition: all 0.3s ease;
      min-height: 120px;
      display: flex;
      flex-direction: column;
      
      &.has-setting {
        background-color: #e8f5e8;
        border-color: #67c23a;
        
        &:hover {
          background-color: #d4edda;
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
        }
      }
      
      &.no-setting {
        background-color: #fff;
        border-style: dashed;
        
        &:hover {
          background-color: #f8f9fa;
          border-color: #409eff;
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
        }
      }
      
      .hour-label {
        font-weight: bold;
        font-size: 14px;
        color: var(--text-primary);
        margin-bottom: 8px;
        text-align: center;
      }
      
      .slot-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 6px;
        
        .price {
          font-size: 18px;
          font-weight: bold;
          color: #e6a23c;
          text-align: center;
        }
        
        .capacity {
          font-size: 14px;
          color: #666;
          text-align: center;
        }
        
        .booking-stats {
          display: flex;
          flex-direction: column;
          gap: 4px;
          margin: 6px 0;
          
          .booking-count {
            font-size: 12px;
            color: #409eff;
            text-align: center;
            font-weight: bold;
          }
          
          .attendance-count {
            font-size: 12px;
            color: #67c23a;
            text-align: center;
            font-weight: bold;
          }
        }
        
        .status {
          text-align: center;
          margin-top: auto;
        }
      }
      
      .no-setting-text {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 14px;
      }
    }
  }
  
  .batch-operations {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;
  }
  
  .dialog-header {
    margin-bottom: 20px;
    
    h4 {
      margin: 0;
      color: #409eff;
      text-align: center;
    }
  }
  
  .batch-hours-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(6, 1fr);
    gap: 10px;
    padding: 16px 8px;
    background: #f8f9fa;
    border-radius: 8px;
    box-sizing: border-box;
    min-width: 100%;
    margin-top: 4px;
    margin-bottom: 4px;
  }
  .styled-batch-grid {
    min-width: 100%;
    max-width: 100%;
  }
}
</style> 